package cn.designpattern.chain;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Chain1 {
    public static void main(String[] args) {
        FilterChain chain = new FilterChain();
        chain.addFilter(new FilterA());
        chain.addFilter(new FilterB());
        chain.addFilter(new FilterC());
        chain.processData(new NumberDouble(2.0));
    }
}

interface IFilter {
    void doFilter(NumberDouble data); // 过滤操作
}

// 过滤器A
class FilterA implements IFilter {
    @Override
    public void doFilter(NumberDouble data) {
        double v = data.getNumber() + data.getNumber();
        data.setNumber(v);
    }
}

// 过滤器B
class FilterB implements IFilter {
    @Override
    public void doFilter(NumberDouble data) {
        double v = data.getNumber() * data.getNumber();
        data.setNumber(v);
    }
}

// 过滤器C
class FilterC implements IFilter {
    @Override
    public void doFilter(NumberDouble data) {
        System.out.println("Filter C: data -> " + data.getNumber());
    }
}

// 过滤器链
class FilterChain {
    private final List<IFilter> filters = new CopyOnWriteArrayList<>();

    public FilterChain() {}

    public void addFilter(IFilter filter) {
        filters.add(filter);
    }

    public void processData(NumberDouble number) {
        for (IFilter filter : filters) {
            filter.doFilter(number);
        }
    }
}

class NumberDouble {
    private double number;

    public double getNumber() {
        return number;
    }

    public void setNumber(double number) {
        this.number = number;
    }

    public NumberDouble(double number) {
        this.number = number;
    }
}